# coding=utf-8
from string import Template
from typing import List
from generator.libsomeip.some_ip_type import Message, SomeIP

from utils.util import  writeFile

NetSomeIPConfig_h=Template(
"""#pragma once

#include <vector>
#include <vsomeip/vsomeip.hpp>
#include "someip/someip_structs.h"

namespace ecarx::transfer::someip {

struct event_info{
    vsomeip::eventgroup_t eventgroup_id;
    std::vector<vsomeip::event_t> event_ids;
};

struct service_info {
    vsomeip::service_t service_id;
    std::vector<event_info> events;
    
};

//作为服务端需要发布的服务以及event事件
const std::vector<service_info> offer_service_infos = {
${service_config}
};

// client to service订阅的事件信息
const std::vector<service_info> request_event_infos = {
${client_configs}
};

} // namespace ecarx::net::someip
"""
)

configs_Templete=Template(
"""
    {
        .service_id=${serviceId},
        .events={
${events}
        }
    }
"""
)

event_templete=Template(
"""
            {
                .eventgroup_id=${eventGroup},
                .event_ids={
                    ${event_ids}
                }
            }
"""
)

class EventGroup:

    def __init__(self,groupId:str) -> None:
        if groupId.strip() == "":
            groupId ="0"
        self.eventGroup=groupId
        self.event_ids=[]

    def __eq__(self, __o: object) -> bool:
        return self.eventGroup == __o.eventGroup

class Service:
    def __init__(self,service_id:str) -> None:
        self.service_id=service_id
        self.eventGroups:List[EventGroup]=[]

    def __eq__(self, __o: object) -> bool:
        return self.service_id == __o.service_id


def gen_SomeIPConfig(someIP:SomeIP):
    offer_configs=[]
    request_configs=[]
    event_configs=[]
    for key,value in someIP.eventGroupDict.items():
        event_ids=[]
        for e in value:
            event_ids.append(e.idtName+"Event")
        event_configs.append(event_templete.substitute(
            eventGroup=key,
            event_ids=",\n\t\t\t\t".join(event_ids)
        ))

    request_configs.append(configs_Templete.substitute(
        serviceId="ADCU_HMI_SERVICE_ID",
        events=",".join(event_configs)
    ))
    

    writeFile("./data/transfer/libsomeip/src", "SomeIPConfig.h",lambda file:file.write(NetSomeIPConfig_h.substitute(
        service_config=",".join(offer_configs),
        client_configs=",".join(request_configs)

    )))
    
        

